//
//  YSHomeViewController.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/5/6.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import HandyJSON
import PullToRefresh
import Alamofire
import SwiftyJSON

class YSHomeViewController: UITableViewController , SliderGalleryControllerDelegate {
    

    var models : [XianhuoModel] = []
    var buttons : HomeButtons?
    let banner = SliderGalleryPresenter()
    var pageNum = 0
    var bannerModels : [YSBanner] = []
    let bottomRefreher = PullToRefresh(position: .bottom)
    var heights : [Int:CGFloat] = [:]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "云数智惠"
        self.banner.delegate = self
        self.automaticallyAdjustsScrollViewInsets = false
        self.tableView.separatorStyle = .none
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        self.tableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
//        self.tableView.estimatedRowHeight = 150
//        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.request();
        
        self.setupPullToRefresh()
        
        self.setupHeader()
        
        if(User.isLogin()){
            User.get.update() //更新通讯录权限
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        self.navigationController?.navigationBar.setBackgroundImage(UIUtility.createImageWithColor(Const.WTM_GREEN), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.barTintColor = Const.WTM_GREEN
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.setTitleFont(UIFont.systemFont(ofSize: 18), color: UIColor.white)

        self.tableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
//        self.tableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        self.navigationController?.navigationBar.setBackgroundImage(UIUtility.createImageWithColor(UIColor.white), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        self.navigationController?.navigationBar.tintColor = Const.WTM_GREEN
        self.navigationController?.navigationBar.setTitleFont(UIFont.systemFont(ofSize: 18), color: Const.WTM_GREEN)
    }
    
    deinit {
        if let head = tableView.topPullToRefresh{
            self.tableView.removePullToRefresh(at: .top)
        }
        if let btm = tableView.bottomPullToRefresh{
            self.tableView.removePullToRefresh(at: .bottom)
        }
    }
    
    func setupHeader() {
        
        let imageView = UIImageView.init(image: UIImage.init(named: "userinfo"))
        imageView.frame = CGRect.init(x: -10, y: 0, width: 30, height: 30)
        imageView.isUserInteractionEnabled = true
        let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(YSHomeViewController.enterUserInfo))
        imageView.addGestureRecognizer(tap1)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: imageView)
        
        let imageView2 = UIImageView.init(image: UIImage.init(named: "setting"))
        imageView2.frame = CGRect.init(x: 10, y: 0, width: 30, height: 30)
        imageView2.isUserInteractionEnabled = true
        let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(YSHomeViewController.enterSetting))
        imageView2.addGestureRecognizer(tap2)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: imageView2)
    }
    
    func setupPullToRefresh() {
        self.tableView.addPullToRefresh(PullToRefresh()) { [weak self] in
            self?.refresh()
        }
        self.addRefreshFooter()
    }
    
    func addRefreshFooter() -> Void {
        self.tableView.addPullToRefresh(bottomRefreher) { [weak self] in
            if self == nil {
                return
            }
            self!.loadmore()
        }
    }
    
    func removeRefreshFooter() -> Void {
        self.tableView.removePullToRefresh(at: .bottom)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // MARK :- tableView
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count + 2
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return Const.SCREEN_WIDTH * 0.432 + Const.ONE_PIXEL;
        }else if indexPath.row == 1 {
            return 150
        }else {
            return self.heightOf(indexPath.row - 2)
        }
    }

    func heightOf(_ index: Int) -> CGFloat {
        if let height = self.heights[index], height > 0 {
            return height
        }
        let xianhuo = models[index]
        let height = self.heightOfXianhuo(xianhuo)
        self.heights[index] = height
        return height
    }
    
    func heightOfXianhuo(_ xianhuo: XianhuoModel) -> CGFloat {
        
        let width = Const.SCREEN_WIDTH - 100 - 10
        var titleHeight = UIUtility.calcStringHeight("今日报价信息：" + xianhuo.advert, font: UIFont.systemFont(ofSize: 17), refWidth: width)
        
        if titleHeight / 17 > 4 {
            titleHeight = 17 * 4
        }else {
            titleHeight -= 2 * titleHeight / 17 //行间距
        }
        let height = 27 + titleHeight + 15 + 34

        return height  //>= 100 ? height : 100
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let reuseId = "banner"
            if let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) {
                return cell
            }
            let cell = UITableViewCell.init(style: .default, reuseIdentifier: reuseId)
            cell.contentView.backgroundColor = Const.WTM_GRAY
            cell.contentView.addSubview(banner.view)
            return cell
        }else if indexPath.row == 1 {
            let reuseId = "buttons"
            if let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) {
                buttons = cell as? HomeButtons
                buttons?.navigationController = self.navigationController
                return cell
            }
            buttons = UITableViewCell.init(style: .default, reuseIdentifier: reuseId) as? HomeButtons
            buttons?.navigationController = self.navigationController
            return buttons!
        }else {
            let cell:HomeXianhuoCell = tableView.dequeueReusableCell(withIdentifier: "homexianhuo") as! HomeXianhuoCell
            let xianhuo = self.models[indexPath.row - 2]
            cell.titleLabel.text = "今日报价信息：" + xianhuo.advert
            cell.companyLabel.text = xianhuo.company
            cell.categoryLabel.text = xianhuo.productname
            cell.index = indexPath.row
            cell.onTapImage = { [weak self] index in
                if let strongSelf = self{
                    let xianhuo = strongSelf.models[index - 2]
                    let vc:ImageViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: ImageViewController.VCID) as! ImageViewController
                    vc.imageUrl = xianhuo.kucunpic
                    strongSelf.navigationController?.pushViewController(vc, animated: true)
                }
            }
            if (xianhuo.productname.count > 0) {
                cell.categoryLabel.text = "\(xianhuo.channelname)(\(xianhuo.productname))"
            }else {
                cell.categoryLabel.text = xianhuo.channelname
            }
            cell.dateLabel.text = xianhuo.getDate()
            cell.locationLabel.text = xianhuo.place
            cell.iconView.kf.setImage(with:URL(string:xianhuo.kucunpic))
            cell.contentView.setNeedsLayout()
            return cell
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row < 2 {
            return
        }
        let xianhuo = self.models[indexPath.row - 2]
        let vc = XianhuoDetailVC2.init()
        vc.url = vc.SHARE_URL + xianhuo.xianhuoId + "&fromApp=1"
        vc.model = xianhuo
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK:- request
    func request() {
        self.checkUpdate()
        self.requestBanner()
        self.refresh()
    }
    
    func requestBanner() {
        
        _ = NetworkManager.GET(NetworkManager.HOMEPAGE) { (status, response) in
//            result.get("pic")
//            updateBanner(pics);
            if status {
                let pics : [Any] = response.wtmDic["pic"] as! [Any]
                self.bannerModels = pics.map({ (dic) -> YSBanner in
                    JSONDeserializer<YSBanner>.deserializeFrom(dict:dic as? NSDictionary)!
                })
                self.banner.setupViews()
            }
        }
    }
    
    func refresh() {
        var params = ["advert":"1","audit":"1","page":"1","type":"0"]
        
        if(User.isLogin()){
            params["channelname"] = User.get.channels
        }
        
        _ = NetworkManager.GET(NetworkManager.XIANHUO_LIST,params:params) { (status, response) in
            self.tableView.endRefreshing(at: .top)
            if(status){
                self.models.removeAll()
                self.heights.removeAll()
                for dic in response.wtmList {
                    let member = JSONDeserializer<XianhuoModel>.deserializeFrom(dict:dic as? NSDictionary)
                    self.models.append(member!)
                }
                self.pageNum += 1;
                self.tableView.reloadData()
            }
        }
    }
    
    func loadmore() {
        let pageNumStr = String(pageNum)
        let params = ["advert":"1","audit":"1","page":pageNumStr,"type":"0"]
        
        _ = NetworkManager.GET(NetworkManager.XIANHUO_LIST,params:params) { (status, response) in
            self.tableView.endRefreshing(at: .bottom)
            self.pageNum += 1;

            for dic in response.wtmList {
                let member = JSONDeserializer<XianhuoModel>.deserializeFrom(dict:dic as? NSDictionary)
                self.models.append(member!)
            }
            if response.wtmList.count < 10 {
                self.removeRefreshFooter()
            }
            self.tableView.reloadData()

        }
    }
    
    func checkUpdate(){
    
        let req = AF.request("http://itunes.apple.com/lookup?id=1249805542")
        req.responseJSON { response in
            
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                if let results = json["results"].array {
                    let versionString = results[0]["version"].stringValue
                    let localVersionString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
                    if self.needUpdate(localVersionString, remote:versionString) {
                        let alert = UIAlertController(title: "提示", message:"发现新版本，立刻去升级吗？", preferredStyle: UIAlertController.Style.alert)
                        let action = UIAlertAction.init(title: "去升级", style: .destructive, handler: { (action1) in
                            let str = NetworkManager.urlencode("https://itunes.apple.com/cn/app/云数智惠/id1249805542?mt=8")
                            UIApplication.shared.openURL(URL.init(string: str)!)
                        })
                        alert.addAction(action)
                        let action2 = UIAlertAction.init(title: "稍后再说", style: .cancel, handler:nil)
                        alert.addAction(action2)
                        self.navigationController?.present(alert, animated: true, completion: nil)
                    }
                    
                }
            default:
                break
            }
        }
    }
    
    func needUpdate(_ local:String , remote:String) -> Bool {

        let localAry = local.components(separatedBy: ".")
        let remoteAry = remote.components(separatedBy: ".")

        var localInt = 0
        var remoteInt = 0
        
        localInt += (Int(localAry[0]) ?? 0) * 10000
        localInt += (Int(localAry[1]) ?? 0) * 100
        localInt += (Int(localAry[2]) ?? 0) * 1
        
        if remoteAry.count < 3{
            return false;
        }
        remoteInt += (Int(remoteAry[0]) ?? 0) * 10000
        remoteInt += (Int(remoteAry[1]) ?? 0) * 100
        remoteInt += (Int(remoteAry[2]) ?? 0) * 1
        
        return localInt < remoteInt;
    }
    
    // MARK:- banner delegate
    //获取数据源
    func galleryDataSource()->[String] {
        return self.bannerModels.map{
            $0.url
        }
    }
    //获取内部scrollerView的宽高尺寸
    func galleryScrollerViewSize()->CGSize {
        return CGSize.init(width: Const.SCREEN_WIDTH, height: Const.SCREEN_WIDTH * 0.432)
    }
    
    func galleryViewTapped(_ index:Int) {
        let vc:ImageViewController = self.storyboard?.instantiateViewController(withIdentifier: ImageViewController.VCID) as! ImageViewController
        vc.imageUrl = self.bannerModels[index].url
        self.navigationController?.pushViewController(vc, animated: true)
    }

    //MARK:- Action
    @objc func enterUserInfo() {
        if !User.isLogin() {
            let vc:LoginVC = UIStoryboard.init(name: "User", bundle: Bundle.main).instantiateViewController(withIdentifier: LoginVC.VCID) as! LoginVC
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        
        let vc:UserActionVC = UIStoryboard.init(name: "User", bundle: Bundle.main).instantiateViewController(withIdentifier: UserActionVC.VCID) as! UserActionVC
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func enterSetting() {
        let vc = SettingVC.init()
        self.navigationController?.pushViewController(vc)
    }
    
}
